package com.tencent.wxcloudrun.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.wxcloudrun.constant.RedisKeyConstant;
import com.tencent.wxcloudrun.domain.TUserCard;
import com.tencent.wxcloudrun.dto.StoreCardQueryCountResDTO;
import com.tencent.wxcloudrun.dto.UserCardListResDTO;
import com.tencent.wxcloudrun.exception.BusinessException;
import com.tencent.wxcloudrun.mapper.TUserCardMapper;
import com.tencent.wxcloudrun.service.TUserCardService;
import com.tencent.wxcloudrun.util.RedisUtil;
import com.tencent.wxcloudrun.vo.request.card.UserCardUseReqVo;
import com.tencent.wxcloudrun.vo.response.card.StoreCardQueryUserCountResVo;

/**
 * @author ziyin.zhao
 * @description 针对表【t_user_card(用户卡片表)】的数据库操作Service实现
 * @createDate 2025-04-22 16:43:56
 */
@Service
public class TUserCardServiceImpl extends ServiceImpl<TUserCardMapper, TUserCard> implements TUserCardService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<UserCardListResDTO> listCard(Long userId) {
        String userCardStr = redisUtil.get(RedisKeyConstant.getUserCardRedisKey(userId));
        if (StringUtils.hasLength(userCardStr)) {
            return JSONObject.parseObject(userCardStr, List.class);
        }
        List<UserCardListResDTO> resDTOList = this.baseMapper.listCard(userId, null);
        if (!CollectionUtils.isEmpty(resDTOList)) {
            this.saveRedis(userId, resDTOList);
        }
        return resDTOList;
    }

    @Override
    public void saveCard(Long userId, Long cardId, Integer count) {
        LambdaQueryWrapper<TUserCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TUserCard::getUserId, userId);
        queryWrapper.eq(TUserCard::getCardId, cardId);
        queryWrapper.eq(TUserCard::getEnableFlag, 1);
        List<TUserCard> userCardList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(userCardList)) {
            // 新增
            TUserCard userCard = new TUserCard();
            userCard.setUserId(userId);
            userCard.setCardId(cardId);
            userCard.setCount(count);
            userCard.setCreatedBy(String.valueOf(userId));
            userCard.setUpdatedBy(String.valueOf(userId));
            userCard.setCreatedTime(LocalDateTime.now());
            userCard.setUpdatedTime(LocalDateTime.now());
            this.save(userCard);
        } else {
            // 更新
            for (TUserCard userCard : userCardList) {
                userCard.setCount(userCard.getCount() + count);
                userCard.setUpdatedBy(String.valueOf(userId));
                userCard.setUpdatedTime(LocalDateTime.now());
            }
            this.updateBatchById(userCardList);
        }

        // 更新缓存
        List<UserCardListResDTO> resDTOList = this.baseMapper.listCard(userId, null);
        if (!CollectionUtils.isEmpty(resDTOList)) {
            this.saveRedis(userId, resDTOList);
        }
    }

    @Override
    public List<StoreCardQueryCountResDTO> queryCount() {
        return this.baseMapper.queryCount();
    }

    @Override
    public List<StoreCardQueryUserCountResVo> queryUserCount(Page<StoreCardQueryUserCountResVo> page, Long cardId,
        List<Long> userIdList) {
        return this.baseMapper.queryUserCount(page, cardId, userIdList);
    }

    @Override
    public void use(UserCardUseReqVo reqVo) {
        LambdaQueryWrapper<TUserCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TUserCard::getUserId, reqVo.getUserId());
        queryWrapper.eq(TUserCard::getCardId, reqVo.getCardId());
        queryWrapper.eq(TUserCard::getEnableFlag, 1);
        List<TUserCard> userCardList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(userCardList)) {
            throw new BusinessException("卡片数量不足");
        }
        // 更新
        for (TUserCard userCard : userCardList) {
            if (userCard.getCount() <= 0) {
                throw new BusinessException("卡片数量不足");
            }
            userCard.setCount(userCard.getCount() - 1);
            userCard.setUpdatedBy(String.valueOf(reqVo.getUserId()));
            userCard.setUpdatedTime(LocalDateTime.now());
        }
        this.updateBatchById(userCardList);

        // 更新缓存
        List<UserCardListResDTO> resDTOList = this.baseMapper.listCard(reqVo.getUserId(), null);
        if (!CollectionUtils.isEmpty(resDTOList)) {
            this.saveRedis(reqVo.getUserId(), resDTOList);
        }
    }

    /**
     * @Author: ZhaoZiYin
     * @Date: 2025/5/13
     * @Params: [userId, resDTOList]
     * @Return: void
     * @Description: 保存缓存
     */
    private void saveRedis(Long userId, List<UserCardListResDTO> resDTOList) {
        redisUtil.set(RedisKeyConstant.getUserCardRedisKey(userId), JSONObject.toJSONString(resDTOList));
    }
}
